# coding=utf-8
import time
import base64
import rsa
import winreg as wg
import datetime
#import maya.cmds as cmds
#import pipeline
#import core as core

# 查询
def registryQuery():
	try:
		handle = wg.OpenKeyEx(wg.HKEY_CURRENT_USER, 'SOFTWARE\RareWolf\Licenses')
		# print handle
		# wg.EnumKey(handle,0)
		# print wg.QueryInfoKey(handle)
		location, _type = wg.QueryValueEx(handle, 'TimeExtension')  #
		#print location
		return (location)
	except:

		return

# 写入
def TimeExtension(inputKey):
	keyPath = r'SOFTWARE\RareWolf'
	key = wg.OpenKey(wg.HKEY_CURRENT_USER, keyPath)
	# print wg.EnumValue(key, 0)
	# 获取该键的所有键值，因为没有方法可以获取键值的个数，所以只能用这种方法进行遍历
	ValueNamekey = wg.EnumKey(key, 0)
	newKeyPath = str(keyPath + '\\' + ValueNamekey)
	# print newKeyPath
	newKey = wg.OpenKey(wg.HKEY_CURRENT_USER, newKeyPath)
	Keys = []
	try:
		i = 0
		while True:
			# EnumValue方法用来枚举键值，EnumKey用来枚举子键10
			name, value, type = wg.EnumValue(newKey, i)
			Keys.append(name)
			i += 1
	except WindowsError:
		print
	# print Keys
	for ValueName in Keys:
		if 'TimeExtension' in ValueName:
			gengxin = wg.CreateKey(key, ValueNamekey)
			wg.SetValueEx(gengxin, "TimeExtension", '', wg.REG_SZ, inputKey)
		else:
			TimeExtension = wg.CreateKey(key, ValueNamekey)
			wg.SetValueEx(TimeExtension, "TimeExtension", '', wg.REG_SZ, inputKey)
#解密
def decrypt(encryption_text):
	with open(pipeline.PythonRootPath() +'/core/bridge/pem/Private_key.pem', 'rb') as Private_key:
		p = Private_key.read()
	try:
		cipher_text = (base64.b64decode(encryption_text))  # base64 解密
		secret_key = rsa.PrivateKey.load_pkcs1(p)
		Decrypt_content = rsa.decrypt(cipher_text, secret_key).decode()  # 注意，这里如果结果是bytes类型，就需要进行decode()转化为str

		#机器码拆解密
		t = ''
		for keys in range(len(Decrypt_content)):
			if keys % 2 == 0:
				t += Decrypt_content[keys]
		return(t)
		# 机器码拆解密
	except:
		return (0)


def Getregistry():
	Getlicense = (decrypt(registryQuery()))
	print(5555555555)
	if type(Getlicense) != "float":
		timestamp = float(Getlicense)
	elif type(Getlicense) == 'str':
		return
	is_base64_code(Getlicense)
	GetregistryTime = (datetime.datetime.fromtimestamp(timestamp))
	# x= (d+datetime.timedelta(days=-3)).strftime("%Y%m%d")
	# 获取当前时间
	loctTime = datetime.datetime.now()
	day = (GetregistryTime - loctTime).days
	return (day)

#####判断否为注册码
def is_base64_code(Getlicense):
	try:
		#print isinstance(Getlicense, str)
		_base64_code = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I','J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R','S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a','b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
						'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's','t', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1','2', '3', '4', '5', '6', '7', '8', '9', '+','/', '=']
		_base64_code_set = set(_base64_code)  # 转为set增加in判断时候的效率
		code_fail = [i for i in Getlicense if i not in _base64_code_set]
		if code_fail or len(Getlicense) % 4 != 0:
			return False
		else:
			if not decrypt(Getlicense):
				return False
			else:
				TimeExtension(Getlicense)
				return True
	except:
		cmds.inViewMessage(amg=u"通知" + u" <hl>注册信息无效，请注册后使用 </hl>", pos='midCenter', fade=True)
		return
